﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using ajayumi.develop.win32.Transport.AppUpgrade.Provider;

namespace ajayumi.develop.win32.Transport.AppUpgrade.Controls
{
    /// <summary>
    /// UcRestoring.cs 还原
    /// Author   : 黄乙冬
    /// Date     : 2011-12-13
    /// </summary>
    public partial class UcRestoring : UcBase
    {
        private AppPackageProvider m_AppProvider = null;

        public UcRestoring()
        {
            InitializeComponent();
        }

        public UcRestoring(UcBase preControl)
            : base(preControl)
        {
            InitializeComponent();
        }

        protected override void InitDefaultValue()
        {
            base.InitDefaultValue();

            this.Title = "程序还原";
        }

        internal override UcBase Next()
        {
            return new UcFinishRestore(this);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.SetButtonVisible(WizardFormButtons.Exit);
            this.pgb.Style = ProgressBarStyle.Marquee;

            this.m_AppProvider = new ZipProvider();
            this.backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                // 关闭待升级的应用程序
                Process[] processes = Process.GetProcessesByName(ArgumentSerialization.ProcessName);
                foreach (Process item in processes)
                {
                    MessageBox.Show("程序正在运行，请做好保存工作，然后关闭程序。还原操作将在程序关闭后继续运行。",
                        "警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    item.WaitForExit();
                }

                bool isSuccess = this.m_AppProvider.Restore();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.pgb.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.PerformNext();
        }
    }
}
